package org.bonorsoft.common.util;

import cn.hutool.core.codec.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.*;
import java.util.*;

public class WxUtil {

    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    /**
     * 解密手机号
     * @author
     * @param session_key
     * @param encryptedData
     * @param iv
     * @return
     */
    public static String analysisPhoneNumber(String session_key,String encryptedData,String iv ) {
        byte[] dataByte = cn.hutool.core.codec.Base64.decode(encryptedData);
        byte[] keyByte = cn.hutool.core.codec.Base64.decode(session_key);
        byte[] ivByte = Base64.decode(iv);
        try {
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String readInterFaceFromUrlByUTF8(String UrlStr) {
        return readInterFaceFromUrl(UrlStr, "utf-8");
    }

    public static String readInterFaceFromUrl(String UrlStr, String encode) {
        if (UrlStr.equalsIgnoreCase("") || UrlStr == null)
            return "";
        String reVal = "";
        URL url;
        HttpURLConnection httpConnection = null;
        try {
            url = new URL(UrlStr);
            URLConnection URLconnection = url.openConnection();
            httpConnection = (HttpURLConnection) URLconnection;
            // httpConnection.setRequestMethod("POST");
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream urlStream = httpConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(urlStream, encode));
                String sCurrentLine = "";
                StringBuilder sTotalString = new StringBuilder();
                while ((sCurrentLine = bufferedReader.readLine()) != null) {
                    sTotalString.append(sCurrentLine);
                }
                reVal = sTotalString.toString();
            } else {
                System.err.println("读取接口失败");
            }
        } catch (Exception e) {
            // e.printStackTrace();
            System.err.println("读取接口异常");
            reVal = "";
        } finally {
            assert httpConnection != null;
            httpConnection.disconnect();
        }
        return reVal;
    }
}
